package cn.littlehx.myweb.service.Impl;

import cn.littlehx.myweb.dao.ICaptchaDao;
import cn.littlehx.myweb.domain.Captcha;
import cn.littlehx.myweb.service.ICaptchaService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

@Service
@Slf4j
public class CaptchaServiceImpl extends ServiceImpl<ICaptchaDao, Captcha> implements ICaptchaService {



    @Autowired
    private ICaptchaDao captchaDao;
    /**
     * 创建验证码,并插入数据库
     * @return
     */
    @Override
    public String generateCaptcha(String email) {
        StringBuilder stringBuilder = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            stringBuilder.append(String.valueOf(random.nextInt(10)));
        }
        String captcha = stringBuilder.toString();
        log.info("生成的验证码是{}", captcha);
        Captcha captcha1 = new Captcha();
        captcha1.setCaptcha(captcha);
        captcha1.setEmail(email);
        captchaDao.insert(captcha1);
        return captcha;
    }


    @Override
    public Boolean confirmCaptcha(String email, String captcha) {
        LambdaQueryWrapper<Captcha> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Captcha::getEmail,email);
        wrapper.eq(Captcha::getCaptcha,captcha);
        wrapper.eq(Captcha::getFlag,1);
        List<Captcha> captchas = captchaDao.selectList(wrapper);
        for (Captcha captchaNow:
             captchas) {
            //如果创建时间在五分钟之内并相同,则表示成功
            if(captchaNow.getCreateTime().isAfter(LocalDateTime.now().minusMinutes(5))&& captchaNow.getCaptcha().equals(captcha)){
                return true;
            }
        }
        return false;
    }
}
